<?php
namespace App\Http\Controllers\Wechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
/**
 * Description of IndexController
 *
 * @author Administrator
 */
class IndexController extends \App\Http\Controllers\Controller{
    private $data   = "";
    private $token  = "";
    public function index(Request $request) {
        $wechat = new \Wechat($request);
        $this->data = $wechat->wechatGetData();
        $this->token = $wechat->wechatGetToken();
        $this->process();
    }
    
    /**
     * 处理接收到的用户关注扫码、点击连接事件
     */
    private function process() {
        if ($this->data->MsgType == "event" && $this->data->Event == "subscribe") {
            $openid = $this->data->FromUserName;
            $user = \App\Models\User::getUser($openid, $this->token);
            $textTpl = <<<EOT
                    <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>
EOT;
            $resultStr = sprintf($textTpl, $this->data->FromUserName, $this->data->ToUserName, time(), config('global.site.wechat.subscribe'));
            exit($resultStr);
        } elseif ($this->data->MsgType == "event" && $this->data->Event == "SCAN") {
            $openid = $this->data->FromUserName;
            $user = \App\Models\User::getUser($openid, $this->token);
        } elseif ($this->data->MsgType == "event" && $this->data->Event == "VIEW") {
            if(!Session::get('home')) {
                $openid = $this->data->FromUserName;
                $user = \App\Models\User::getUser($openid, $this->token);
            }
        }
    }
    /**
     * 获取用户信息并注册或者登录
     */
    public function getUinfo(Request $request) {
        if ($request->input('code')) {
            $user = \App\Models\User::regUser($request->input('code'), $request->input('refperson'));
            if ($user) {
                return redirect(url('home/index/index'));
            }
        } else {
            return redirect(url('home/index/index'));
        }
        
    }
}
